class websocket {
	constructor(url, onReceive) {
		this.is_open_socket = false //避免重复连接
		this.url = url //地址
		this.data = null
		this.reconnectTimeOut = null //重连之后多久再次重连
		this.onReceive = onReceive
		this.socketTask = null
	}
	connectSocketInit() {
		this.socketTask = uni.connectSocket({
			url: this.url,
			header: {
				token: uni.getStorageSync("token")
			},
			success: () => {
				console.log("正准备建立websocket中...");
				// 返回实例
				// return this.socketTask
			},
		});
		this.socketTask.onOpen((res) => {
			console.log("WebSocket连接正常！");
			clearTimeout(this.reconnectTimeOut)
			this.is_open_socket = true;
			// 注：只有连接正常打开中 ，才能正常收到消息
			this.socketTask.onMessage((res) => {
				// console.log(res.data)
				this.onReceive(res.data)
			});
		})
		// 这里仅是事件监听【如果socket关闭了会执行】
		this.socketTask.onClose(() => {
			console.log("已经被关闭了")
			if (this.is_open_socket === true)
				this.reconnect();
		})
	}
	//发送消息
	send(value) {
		// 注：只有连接正常打开中 ，才能正常成功发送消息
		this.socketTask.send({
			data: JSON.stringify(value),
			async success() {
				console.log("消息发送成功");
			},
		});
	}
	reconnect() {
		//如果不是人为关闭的话，进行重连
		this.reconnectTimeOut = setTimeout(() => {
			this.connectSocketInit();
		}, 3000)
	}
	close() {
		this.is_open_socket = false
		uni.closeSocket({
			success() {
				console.log("WebSocket关闭成功")
			}
		})
	}
}
module.exports = websocket
